package com.example.pengxiangedupay.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.pengxiangedupay.common.utils.R;
import com.example.pengxiangedupay.dto.UpdatePasswordDto;
import com.example.pengxiangedupay.entity.PaySysUser;
import com.example.pengxiangedupay.service.PaySysUserService;
import com.example.pengxiangedupay.service.StuBaseInfoService;
import com.example.pengxiangedupay.vo.LoginVo;
import com.example.pengxiangedupay.vo.StuInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/app")
public class SysController {
    @Autowired
    PaySysUserService paySysUserService;
    @Autowired
    StuBaseInfoService stuBaseInfoService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @ResponseBody
    @PostMapping("/login")
    public R login(@RequestBody LoginVo loginVo,HttpServletRequest request, HttpServletResponse response){
        //获取Cookie中的uuid
        String struuid = null;
        //获取cookie里面的uuid
        Cookie[] cookies = request.getCookies();
        if(cookies != null){
            for (Cookie cookie : cookies) {
                if (cookie.getName().equalsIgnoreCase("userCookie")) {
                    struuid = cookie.getValue();
                }
            }
        }
        String userJson = null;
        if(struuid != null){
            userJson = stringRedisTemplate.opsForValue().get("user" + "/" + struuid);
            if(userJson != null){
                PaySysUser paySysUser = JSON.parseObject(userJson, PaySysUser.class);
                return R.ok("登陆成功").put("data",paySysUser);
            }
        }
        System.out.println("redis验证失败，没有登录记录");
        if(loginVo == null){
            return R.error("登陆失败，登录信息为空");
        }
        //验证账号密码
        PaySysUser user = paySysUserService.getOne(new QueryWrapper<PaySysUser>().eq("username", loginVo.getUsername()));
        if(user==null){
            System.out.println("数据库没有对应用户名");
            return R.error("登陆失败，请检查账号和密码是否正确");
        }
        if(user.getPassword().equals(loginVo.getPassword())){
            String uuid = UUID.randomUUID().toString();
            Cookie cookie = new Cookie("userCookie", uuid);
            response.addCookie(cookie);
            String userJoin = JSON.toJSONString(user);
            stringRedisTemplate.opsForValue().set("user" + "/" + uuid, userJoin, 60, TimeUnit.SECONDS);
            return R.ok("登陆成功").put("data",user);//code为0
        }else{
            System.out.println("密码匹配有误");
            return R.error("登陆失败，请检查账号和密码");
        }
    }
    @ResponseBody
    @RequestMapping("/logout")
    public R logout(HttpServletRequest request){
        //获取Cookie中的uuid
        String struuid = null;
        //获取cookie里面的uuid
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equalsIgnoreCase("userCookie")) {
                struuid = cookie.getValue();
            }
        }
        String userJson = null;
        if(struuid != null){
            userJson = stringRedisTemplate.opsForValue().get("user" + "/" + struuid);
            if(userJson != null){
                stringRedisTemplate.delete("user" + "/" + struuid);
            }
        }
        return R.ok();
    }

    @ResponseBody
    @GetMapping("/info/{stuId}")
    public StuInfoVo getInfo(@PathVariable Long stuId){
        StuInfoVo stuInfo = stuBaseInfoService.getStuInfo(stuId);
        return stuInfo;
    }

    @ResponseBody
    @PostMapping("/update")
    public R update(@RequestBody StuInfoVo stuInfoVo){
        boolean b = stuBaseInfoService.updateById(stuInfoVo);
        if (b){
            return R.ok("修改成功!");
        }
        return R.error("修改失败!");
    }

    @ResponseBody
    @PostMapping("/updatePassword")
    public R updatePassword(@RequestBody UpdatePasswordDto updatePasswordDto){
        LambdaQueryWrapper<PaySysUser> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(PaySysUser::getStuId,updatePasswordDto.getStuId());
        PaySysUser one = paySysUserService.getOne(lambdaQueryWrapper);
        if (updatePasswordDto.getOldPassword().equals(one.getPassword())){
            one.setPassword(updatePasswordDto.getNewPassword());
            paySysUserService.updateById(one);
            return R.ok("修改成功!");
        }
        return R.error("修改失败,原始密码输入错误!");
    }
}
